// 参考项目：https://github.com/wstee/qiankun-web
import { registerMicroApps } from 'qiankun'
import config from './config'
import { useUserStore } from '@/stores'
import { GetMicroApp, type MicroApp } from '@/apis/system/plugins'

let { subApps } = config

export async function registerApps() {
  try {
    // 判断是否是发布环境，发布环境从后台获p取subApps
    if (import.meta.env.PROD) {
      const { data } = await GetMicroApp()
      // 将获取的子应用数据转换为qiankun需要的格式
      subApps = data.map((app) => ({
        name: app.name, // 子应用名称
        entry: app.entry, // 子应用入口地址
        container: '#sub-container', // 子应用挂载节点
        activeRule: app.activeRule, // 子应用激活规则
        props: {
          userInfo: [],
          token: '',
          publicKey: '',
        }, // 主应用与子应用通信传值
        sandbox: {
        // strictStyleIsolation: true, // 启用严格样式隔离
        },
      }))
    }

    registerMicroApps(subApps, {
      beforeLoad: [
        (app) => {
          console.log('[主应用] beforeLoad', app.name)
          const useStore = useUserStore()
          app.props.token = useStore.token
          app.props.userInfo = useStore.userInfo
          app.props.publicKey = import.meta.env.VITE_PUBLIC_KEY
        },
      ],
      // 生命周期钩子
      loader: (loading) => {
        // 可以在这里处理加载状态
        console.log('子应用加载状态:', loading)
      },
      beforeMount: [
        (app) => {
          console.log('[主应用] beforeMount', app.name)
          const container = document.querySelector(app.container)
          if (container) container.innerHTML = ''
        },
      ],
      afterUnmount: [
        (app) => {
          console.log('[主应用] afterUnmount', app.name)
        },
      ],
    })
  } catch (err) {
    console.log(err)
  }
}
